package com.example.goodsass.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.goodsass.common.BaseResponse;
import com.example.goodsass.common.BusinessException;
import com.example.goodsass.common.ErrorCode;
import com.example.goodsass.constans.enums.UserRole;
import com.example.goodsass.domain.User;
import com.example.goodsass.service.UserService;
import com.example.goodsass.mapper.UserMapper;
import com.example.goodsass.vo.UserVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-04-09 20:11:46
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    UserMapper userMapper;

    @Override
    public int delUser(String userid) {
        return userMapper.deleteById(userid);
    }

    public UserVO getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute("loginUser");
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询 确保数据最新
        String userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return BeanUtil.copyProperties(currentUser, UserVO.class);
    }

    public void LoginUserCheck(HttpServletRequest request) {
        UserVO loginUser = this.getLoginUser(request);
        if (!loginUser.getRoleName().equals(UserRole.ADMIN.getValue())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有管理员才可以新增用户");
        }
    }

    public boolean insUserCheck(User user) {
        if (userMapper.selectUserAccount(user.getUserAccount()) != null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "已存在的用户");
        } else if (StrUtil.hasBlank(user.getNickName(), user.getRoleName(), user.getUserAccount(), user.getPassword())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "请检查输入的信息");
        } else {
            return true;
        }
    }
}




